<?php

class Ticket extends Controller {
    
	function setVars(){
		$this->tpl['jsOnLoad']  = '';
		$this->tpl['head'] = '';
		$this->tpl['title'] = 'Help Desk';
        $this->tpl['sidebar'] = '';
        $this->tpl['body'] = '';
		$this->uid = $this->session->userdata('uid');
	}
	
	
	function __construct()
	{
		parent::Controller();	
		log_message('debug', "Ticket: Controler Class Initialized");
        $this->auth->CheckTaMeR(2);
		$this->setVars();
        $this->load->library('table');
        //		$this->load->library('profiler');
	}
    
    /**
    * @note	index
    * @info	Just forwarding
    * @author	Dennis T. Kaplan
    * @access	public
    * @param	 
    * @return	html page
    */	
    public function index()
    {
        //$this->initdb(); 
        if($this->input->post('NewTicket') !== FALSE)
        {
            $this->validate(); 
        }
        elseif($this->input->post('Close') !== FALSE)
        {
            $this->CloseTicket(); 
        }
        elseif($this->input->post('Reply') !== FALSE)
        {
            $this->validateReply(); 
        }
        else
        {
            $this->Browse();
        }
    }
    
	public function Browse()
	{
        //$this->db->select('id' , 'uid', 'Ticket_No' , 'Category' , 'Subject' , 'State');
        if($this->uid == 1){
            $query = $this->db->get('Ticket');
        }else{
        	$query = $this->db->getwhere('Ticket', array('uid' => $this->uid));
        }
		if ($query->num_rows() > 0)
		{
			foreach($query->result_array() as $k => $s):
            $tbresult[$k] = $s;
			endforeach;
			//$tbresult = delids($tbresult);
            
			$this->table->set_heading(array_keys($tbresult[0]));
			foreach($tbresult as $row):
			$v = $row['Ticket_No'];
			$row['Ticket_No'] = anchor('ticket/view/'.$v,$v);
            $this->table->add_row($row);
			endforeach;			
			$this->tpl['body'] .= $this->table->generate();
			$this->table->clear();
		}else{
			redirect('ticket/newTicket', 'location');
		}
        
		$this->load->view('blank', $this->tpl);
	}
	
	
	function validate()
	{
        $this->load->library('validation');
        $rules['Subject']="trim|required|min_length[4]|max_length[80]|xss_clean";
        $rules['Body']  ="trim|required|min_length[10]|max_length[4000]|xss_clean";
        $this->validation->set_rules($rules);
        if($this->validation->run() == FALSE)
        {
            $this->msg->setError('Validation error');
            
            $this->NewTicket();
        }
        else
        {
            $this->load->helper('string');
            $no = random_string('alnum', 10);
            $alias = $this->session->userdata('Alias');
            
            $data = array(
            'uid'		=> $this->uid,
            'Ticket_No'	=> $no,
            'Category'	=> $this->input->post('Category'),
            'Subject' 	=> $this->validation->Subject,
            'State' 		=> 'New'
            );
            $this->db->insert('Ticket', $data);
            
            $tid = $this->db->insert_id();
            
            $this->load->helper('typography');
            
            $data = array(
            'ticket_id'	=> $tid,
            'Alias'		=> $alias,
            'Priority'	=> $this->input->post('Priority'),
            'Message'	=> auto_typography($this->validation->Body)
            );
            $this->db->insert('Ticket_Message', $data);
            redirect('/ticket/view/'.$no, 'refresh');
            
        }
	}
    
	function validateReply()
	{
        $this->load->library('validation');
        $rules['Body'] ="trim|required|min_length[10]|max_length[2000]|xss_clean";
        $this->validation->set_rules($rules);
        if($this->validation->run() === FALSE)
        {
            $this->Ticket_No = $this->input->post('tno');
            $this->db_Ticket_id = $this->input->post('tid');
            $this->view();
        }
        else
        {
            $this->Ticket_No = $this->input->post('tno');
            $this->db_Ticket_id = $this->input->post('tid');
            
            $alias = $this->session->userdata('Alias');
            
            $this->load->helper('typography');
            $data = array(
            'ticket_id'	=> $this->db_Ticket_id,
            'Alias'		=> $alias,
            'Priority'	=> $this->input->post('Priority'),
            'Message'	=> auto_typography($this->validation->Body)
            );
            $this->db->insert('Ticket_Message', $data);
            
            if($this->uid == 1)
            {
                $data = array('State' => 'Pending');
            }else{
            	$data = array('State' => 'Open');
            }
            $this->db->where('id', $this->db_Ticket_id);
            $this->db->update('Ticket', $data);
            
            redirect('/ticket/view/'.$this->Ticket_No, 'location');
        }
	}
    
	function CloseTicket()
	{
        $this->db_Ticket_id = $this->input->post('tid');
        
        $data = array('State' => 'Closed');
        $this->db->where('id', $this->db_Ticket_id);
        $this->db->update('Ticket', $data);
        
        redirect('ticket', 'location');
    }
    
    
	function newTicket()
	{
        $Priority = array(
        'Urgent' => 'Urgent',
        'Medium' => 'Medium',
        'Low' => 'Low'
        );
        
        $Category = array(
        'Sales' => 'Sales',
        'Support' => 'Support',
        'Website' => 'Website'
        );
        
		$form[1]['Priority'] = form_dropdown('Priority', $Priority,'Low');
		$form[1]['Category'] = form_dropdown('Category', $Category,'Sales');
        
        $form[1]['Subject'] = form_input(array(
        'name'        => 'Subject',
        'id'          => 'Subject',
        'value'       =>  '',
        'maxlength'   => '80',
        'size'        => '40',
        'style'       => ''
        )
        );
        $form['Body'] = form_textarea(array(
        'name'        => 'Body',
        'id'          => 'Body',
        'value'       =>  '',
        'rows'        => '20',
        'cols'        => '75',
        'style'       => ''
        )
        );
        $form[''] =          form_submit(array('class' => 'submit', 
        'name'        => 'NewTicket',
        'value'       => 'Submit',
        'style'       => 'margin:10px'
        )
        );
        
        define('URI',$this->uri->segment(1));
        $attributes = array('name' => 'Ticket');
        $this->tpl['body'] .= form_open(URI, $attributes);
        $this->tpl['body'] .= $this->table->form_table($form);
        $this->tpl['body'] .= '</form>';
        
		$this->load->view('blank', $this->tpl);
	}
	
	private function replyForm()
	{
        define('URI',$this->uri->segment(1));
        
        $Priority = array(
        'Urgent' => 'Urgent',
        'Medium' => 'Medium',
        'Low' => 'Low'
        );
        
		$array[1]['Priority'][] = form_dropdown('Priority', $Priority,'Low');
        
        $array['  '] = form_textarea(array(
        'name'        => 'Body',
        'id'          => 'Body',
        'value'       =>  '',
        'rows'        => '10',
        'cols'        => '50',
        'class'       => 'SideBar'
        )
        );
        $array['   '] = form_submit(array('class' => 'submit', 
        'name'        => 'Reply',
        'value'       => 'Reply',
        'style'       => 'margin:10px'
        )
        );
        $form = '';
        $form .= '<div id="show_hide_div">';
        $form .= '<fieldset class="SideBar"><legend class="SideBar">Reply</legend>';
        $form .= '<div id="MessangerCloser"><a href="#" accesskey="Q" onclick="hide(\'show_hide_div\');">X</a></div>';
        $attributes = array('name' => 'Ticket');
        $form .= form_open(URI, $attributes);
        $form .= $this->table->form_table($array);
        $form .= form_hidden('tid', $this->db_Ticket_id);
        $form .= form_hidden('tno', $this->Ticket_No);
        $form .= '</form></fieldset></div>';
        $this->tpl['show_hide'] = $form ;


        /*  Reply Window Control*/
        $array = form_submit(array('class' => 'submit', 
        'name'        => 'Open',
        'value'       => 'Reply',
        'style'       => 'margin:10px',
        'onclick'     => "ShowHide('show_hide_div')"
        )
        );
        $this->tpl['sidebar'] .= $array;
        


        /*      Close Form      */
        $array =          form_submit(array('class' => 'submit', 
        'name'        => 'Close',
        'value'       => 'Close This Ticket',
        'style'       => 'margin:10px'
        )
        );
        $attributes = array('name' => 'Close Ticket');
        $form = form_open(URI, $attributes);
        $form .= $array;
        $form .= form_hidden('tid', $this->db_Ticket_id);
        $form .= form_hidden('tno', $this->Ticket_No);
        $form .= '</form>';
        $this->tpl['sidebar'] .= $form ;
	}
    
    function view()
    {
        $this->tpl['title'] = 'Help Desk';
        
        if ( ! isset($this->Ticket_No)){
        	$this->Ticket_No = $this->uri->segment(3);
        }
        if($this->Ticket_No === FALSE)
		{
			redirect('/ticket', 'location');
		}
        $sql = "SELECT `id`, `Subject`, `Category`, `Ticket_No`, `State` FROM `Ticket` WHERE `Ticket_No` = '$this->Ticket_No' LIMIT 1;";
        $row = $this->db->query($sql);
        if ($row->num_rows() > 0)
        {
            $db_Ticket = $row->row_array();
            $row->free_result();
            $this->db_Ticket_id = $db_Ticket['id'];
            unset($db_Ticket['id']);
            //$this->table->set_heading(array_keys($db_Ticket));
            //$this->table->add_row($db_Ticket);
            //$this->tpl['body'] = $this->table->generate();
            $this->tpl['sidebar'] .= $this->table->form_table($db_Ticket);
			$this->table->clear();
            
            $sql = "SELECT `Alias`, `Priority`, `Date`, `Message` FROM `Ticket_Message` WHERE `ticket_id` = $this->db_Ticket_id";
            $result = $this->db->query($sql);
			foreach($result->result_array() as $k => $s)
            {
                $db_Message[$k] = $s;
			}
			foreach($db_Message as $k=>$v){
				$db_Message[$k]['Date'] = $this->timetamer->ldate($db_Message[$k]['Date']);
			}
            // Restructure db table to view massages in second row.
			foreach($db_Message as $k => $s){
                $query3 = $db_Message[$k];
                unset($query3['Message']);
                $query6[] = $query3;
                $query6[]['Message'] = $db_Message[$k]['Message'];
			}
			$this->table->set_template($this->tb_template());
			$this->table->set_heading(array_keys($query3));
			unset($query3);
			foreach($query6 as $row){
                $this->table->add_row($row);
			}
			$this->tpl['body'] .= $this->table->generate();
			$this->table->clear();
        }
        $this->replyForm();
        $this->load->view('blank', $this->tpl);
    }
    
    
    /**
    * @note	tb_template
    * @info	
    * @author	Dennis T. Kaplan
    * @access	private
    * @param	 
    * @return	string
    */	
    private function tb_template()
    {
        return array (
        'table_open'          => '<table border="1" cellpadding="2" cellspacing="0" width="90%" align="center"><tbody>',
        'heading_row_start'   => '<tr>',
        'heading_row_end'     => '</tr>',
        'heading_cell_start'  => '<th colspan="2">',
        'heading_cell_end'    => '</th>',
        
        'row_start'           => '<tr class="odd">',
        'row_end'             => '</tr>',
        'cell_start'          => '<td  colspan="2" style="text-align: center;padding-top: 15px; ">',
        'cell_end'            => '</td>',
        
        'row_alt_start'       => '<tr class="even">',
        'row_alt_end'         => '</tr>',
        'cell_alt_start'      => '<td colspan="6" style="padding:15px; border-bottom: 7px double  black;">',
        'cell_alt_end'        => '</td>',
        
        'table_close'         => '</tbody></table>'
        );
    }
    
}
?>